/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

//=../Button/Button
//=MenuItem
//=MenuSeparator
//=MenuHeader

/**
 * Toggleable, contextual menu for displaying lists of links.
 *
 * @author Eugene Kuzmenko <mail@aljey.com>
 * @class {Menu}
 * @extends {Container}
 */
Class.define('Menu', {

  extend: 'Container',

  /**
   * A align the menu to either left or right.
   *
   * @property {number}
   * @default 0
   * @example
   *   0 = left
   *   1 = right
   */
  align: 0,

  /** @constructs */
  init: function () {
    _super();
    this.triggerId = this.triggerId || this.uid();
  },

  /** @inheritDoc */
  slots: [{
    name: 'trigger',
    prependMode: true,
    defaults: {type: 'Button', caret: true}
  },{
    name: 'items',
    renderTo: '.dropdown-menu',
    defaults: {type: 'MenuItem'},
    alias: {'-': 'MenuSeparator'}
  }],

  /** @inheritDoc */
  tpl: [
    '<span class="dropdown">',
      '<ul class="dropdown-menu dropdown-menu-<%=(["left","right"])[align]%>"',
        ' role="menu" aria-labelledby="<%=triggerId%>"></ul>',
    '</span>'
  ],

  /**
   * Changes alignment of the menu.
   *
   * @param {Number} val
   * @returns {Menu}
   */
  setAlign: _static.Container.setter(function (val) {
    var dir = ['dropdown-menu-left', 'dropdown-menu-right'];
    this.items.renderTo.removeClass(dir[this.align]).addClass(dir[val]);
  }, 'align', 'number'),

  listeners: {
    beforeRender: function () {
      var last = this.trigger.last;
      last && last.el.attr({'data-toggle': 'dropdown', id: this.triggerId});
    }
  }

});